/**
 * @file
 * @auth jinguangguo
 * @date 2016/12/8
 */

import Vue from 'vue';

import {REG_NUMBER, REG_DECIMAL} from '../common/constants';

Vue.directive('number', {
    deep: true,
    bind(el, binding, vnode) {
        let scope = vnode.context;
        // let vModel = el.getAttribute('v-model');
        // let vModel = binding.expression;

        let precision = binding.value.precision;
        let vModel = binding.value.model;

        let regNumber;
        let regDecimal;
        if(precision>0){
            regNumber = new RegExp('^[1-9]+[0-9]*(\\.\\d{0,' + precision + '})?$');
            regDecimal = new RegExp('^0(\\.\\d{0,' + precision + '})?$');
        }else{
            regNumber = new RegExp('^[1-9]+[0-9]*$');
            regDecimal = new RegExp('^0$');
        }


        let arrs = vModel.split('.');
        let attr0 = arrs[0];
        let attr1 = arrs[1];

        if (vModel) {
            scope.$watch(vModel, (newVal, oldVal) => {
                if (newVal !== '') {
                    if (regNumber.test(newVal) === true || regDecimal.test(newVal) === true) {

                    } else {
                        if (attr1) {
                            scope[attr0][attr1] = oldVal;
                        } else {
                            scope[attr0] = oldVal;
                        }
                    }

                }
            }, {deep: true});
        }
    },
    update(el, binding, vnode) {

    }
});
